﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace Universe.WCF.Behaviors.WcfStreaming
{
    class WcfResponseStream : Stream
    {
        private FileStream _My;
        private long Pos = 0;
        private string NameStream;
        public LengthReference LenRef;
        private WaitHandle _isDone;

        public WcfResponseStream(FileStream my, WaitHandle isDone, string nameStream)
        {
            _My = my;
            _isDone = isDone;
            NameStream = nameStream;
        }

        public override void Flush()
        {
            _My.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int maxCount;
            while (true)
            {
                // long maxCount64 = (int) (_My.Length - Pos);
                long trueLen = Interlocked.Read(ref LenRef.Length);
                long maxCount64 = (int)(trueLen - Pos);
                int limitCount = buffer.Length - offset;
                if (maxCount64 > limitCount)
                    maxCount64 = limitCount;

                long fileLength = _My.Length;
                if (false)
                Console.WriteLine(
                    "LenRef: {6} My.Length: {0}, Pos: {1}, Buffer: {2}-{3}-{4} Limit:{5}", fileLength, Pos, buffer.Length,
                                  offset, count, limitCount, trueLen);

                maxCount = (int) maxCount64;
                if (maxCount > 0)
                    break;

                if (maxCount <= 0)
                {
                    if (trueLen == fileLength)
                        if (_isDone.WaitOne(0))
                            return -1;
                }

                Thread.Sleep(1);
            }

            // Assert
            var filePos = _My.Position;
            if (filePos != Pos) 
                throw new InvalidOperationException("Never goes here: Position Collision Detected");

            // вычитываем maxCount байт
            int readed = 0;
            byte[] buf = new byte[maxCount];
            while (readed < maxCount)
            {
                int r = _My.Read(buf, readed, maxCount - readed);
                if (r > 0)
                    readed += r;
                else
                    Thread.Sleep(0);
            }

            // копируем buf в output-буфер
            for (int i = 0; i < readed; i++)
                buffer[offset + i] = buf[i];

            Pos += readed;
            return readed;

        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override long Length
        {
            get { throw new NotSupportedException(); }
        }

        public override long Position
        {
            get { return Pos; }
            set { throw new NotSupportedException(); }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this._My != null)
                {
                    this._My.Dispose();
                    _My = null;

                    try
                    {
                        File.Delete(NameStream);
                    }
                    catch(Exception ex)
                    {
                        Debug.WriteLine("Failed to delete data stream on dispose: " + ex);
                    }
                }

            }
        }
    }
}
